import * as fs from "fs";
import * as path from "path";
import Parser from "./DotProto/Parser";
import Proto2Json from "./ProtoToJson/Proto2Json";
import Proto2Type from "./ProtoToType/Proto2Type";
function readProto(filename: string): Array<string> {
    let fileArray: Array<string> = new Array();
    if (fs.existsSync(filename)) {
        // 如果是文件夹就把所有的proto 文件proto 给便利一遍
        if (fs.statSync(filename).isDirectory()) {
            readDirSync(filename, fileArray);
        } else {
            fileArray.push(filename);
        }
    }
    return fileArray;
}
function protoParse(fileArray: Array<string>, map: Map<string, any>) {
    for (let i = 0; i < fileArray.length; i++) {
        let filePath = fileArray[i];
        let protoName = path.basename(filePath);
        if (map.has(protoName)) {
            continue;
        }
        let contente = fs.readFileSync(filePath, "utf-8")
        let parse: Parser = new Parser(contente);
        let obj = parse.parse();
        let imp = obj["imports"];
        let newFileArray = new Array();
        map.set(protoName, obj)
        for (let j = 0; j < imp.length; j++) {
            let importPath = path.join(path.dirname(filePath), imp[j])
            newFileArray.push(importPath);
        }
        if (newFileArray.length > 0) {
            protoParse(newFileArray, map);
        }
    }

}
function readDirSync(filePath: string, fileArray: Array<string>) {
    var pa = fs.readdirSync(filePath);
    pa.forEach(function (ele, index) {
        var info = fs.statSync(filePath + "/" + ele)
        if (info.isDirectory()) {
            readDirSync(filePath + "/" + ele, fileArray);
        } else {
            let f = filePath + "/" + ele;
            if (path.extname(f).toLowerCase() == ".proto") {
                fileArray.push(filePath + "/" + ele)
            }
        }
    })
}

function main(filename: string) {
    //let filename = "./test/test.proto"
    let fileArray: Array<string> = readProto(filename);
    let pinusJosn: Array<string> = new Array();
    let map: Map<string, any> = new Map();
    protoParse(fileArray, map);
    map.forEach((val, key) => {
        pinusJosn.push(Proto2Json.toJson(val))
    })
    let json = pinusJosn.join(",")
    json = "{\r\n" + json + "\r\n}"
    console.log(json);

    let pinusType: Array<string> = new Array();
    map.forEach((val, key) => {
        pinusType.push(Proto2Type.toType(val))
    })
    console.log(pinusType.join("\r\n"));
}
let args = process.argv.splice(2);
if (args.length == 1) {
    main(args[0]);
} else {
    main("./test/")
}

